<?php

// Created by Khanh Nam
class InvoicesController extends Controller
{

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'invoice-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionIndex($id=NULL, $type=NULL, $custno=NULL, $locno=NULL)
    {

        switch ($type)
        {
            case Invoice::TYPE_QUOTE:
                $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
                    'custno'    => $custno,
                    'locno'     => $locno)
                );
                if ($location == NULL)
                {
                    throw new CHttpException(404, 'The requested page does not exist.');
                }
                $this->render('index', array(
                    'location'  => $location,
                    'type'      => $type
                ));
                break;
            case Invoice::TYPE_SALES_ORDERS:

                $quote = $this->loadModel($id);
                $this->render('index', array(
                    'model'     => $quote,
                    'location'  => $quote->location,
                    'type'      => $type
                ));
                break;
            case Invoice::TYPE_INVOICE:
                $tabName    = 'Invoice';
                $location   = Locations::model()->find('custno=:custno AND locno=:locno', array(
                    'custno'    => $custno,
                    'locno'     => $locno)
                );
                if ($location == NULL)
                {
                    throw new CHttpException(404, 'The requested page does not exist.');
                }
                $this->render('index', array(
                    'location'  => $location,
                    'type'      => $type
                ));
                break;
        }
    }

    public function actionCancel($invoice, $delete=0)
    {
        $model          = $this->loadModel($invoice);
        /* @var $model Invoice */
        $type           = $model->invoicetype;
        $locno          = $model->locno;
        $custno         = $model->custno;
        $quoteorg       = $model->quoteorg;
        $jobid          = $model->jobnumber;
        $contractid     = $model->agreementno;
        $salesordersorg = $model->salesordersorg;
        $invoiceorg     = $model->invoiceorg;
        if ($delete == 1)
        {
            $model->delete();
        }
        switch ($type)
        {
            case Invoice::TYPE_QUOTE:
                //redirect to quote list
                if ($jobid != NULL)
                {
                    // $model->delete();
                    if ($contractid != NULL)
                    {
                        $this->redirect(array('/contracts/update', 'contractid' => $contractid));
                    }
                    else
                    {
                        $this->redirect(array('/jobs/update', 'jobid' => $jobid));
                    }
                }else
                    $this->redirect(array('/locations/update', 'custno' => $custno, 'locno' => $locno));
                break;
            case Invoice::TYPE_SALES_ORDERS:
                //redirect to quote update page
                if ($quoteorg != NULL)
                    $this->redirect(array('update', 'invoice' => $quoteorg));
                else
                    $this->redirect(array('/locations/update', 'custno' => $custno, 'locno' => $locno));
                break;
            case Invoice::TYPE_INVOICE:
                if ($salesordersorg != NULL)
                    $this->redirect(array('update', 'invoice' => $salesordersorg));
                else
                    $this->redirect(array('/locations/update', 'custno' => $custno, 'locno' => $locno));
                break;
            case Invoice::TYPE_CREDIT_MEMO:
                if( $invoiceorg !=null){
                    $this->redirect(array('update','invoice'=>$invoiceorg));
                }else{
                    $this->redirect(array('/locations/update', 'custno' => $custno, 'locno' => $locno));
                }
                break;
        }
    }

    public function actionUpdate($invoice)
    {

        $model      = $this->loadModel($invoice);
        $tabName    = '';
        switch ($model->invoicetype)
        {
            case Invoice::TYPE_QUOTE:
                $tabName = 'Quote';

                break;
            case Invoice::TYPE_SALES_ORDERS:
                $tabName = 'Sales Order';

                break;
            case Invoice::TYPE_INVOICE:
                $tabName = 'Invoice';
                break;
        }
        Yii::app()->clientScript->registerScript('typeLabel', "var typeLabel='$tabName'", CClientScript::POS_HEAD);


        
        outputJsByList(ContactUtil::getContactData($model->custno, $model->locno, $model->salesperson), 'contacts');
        if (isset($_POST['Invoice']))
        {
            //$this->performAjaxValidation($model);
            /* @var $model Invoice */
            $model->attributes  = $_POST['Invoice'];
            $model->status      = 0;
            

            if (($model->isEditable() || InvoiceUnlocker::isInvoiceUnlocked($invoice)) && $model->save())
            {
                InvoiceUnlocker::lockAllInvoice();
                // echo 'Saved invoice';
                //specific for invoice
                if ($model->invoicetype == Invoice::TYPE_CREDIT_MEMO)
                {
                    Inventoryact::insertFromInvoiceItem($model->invoice);
                }

                if ($model->invoicetype == Invoice::TYPE_INVOICE)
                {
                    if ($model->createTransactionRecord() == false)
                    {
                        echo 'false';
                        Yii::app()->end();
                    }
                    else
                    {
                      
                        Inventoryact::insertFromInvoiceItem($model->invoice);
                    }
                }
                //$transaction->commit();
                //Yii::app()->end();
            }
            else
            {
                echo 'false';
                Yii::app()->end();
            }

            echo 'true';
            Yii::app()->end();
        }
        outputJsByList(Warehouse::model()->getList(), 'warehouse');
        outputJsByList(Employees::model()->getEmployeeList(), 'employee');
        outputJsByList(Equipment::model()->getListByLocation($model->custno, $model->locno), 'equipment');
        $invoiceLedger = InvoiceLedger::model()->findAll('invoice=:invoice', array('invoice' => $model->invoice));
        $itemsList = array();
        foreach ($invoiceLedger as $i => $item)
        {
            $itemsList[]                    = $item->attributes;
            $itemsList[$i]['price']         = $item->price;
            $itemsList[$i]['noprinttext']   = $item->getYesNoValue($item->noprint);
            $itemsList[$i]['taxedtext']     = $item->getYesNoValue($item->taxed);
        }
          if($model->discounted){
            $discount = new InvoiceLedger();
            $discount->price = $model->discount_percent;
            $discount->description = $model->discount_memo;
            $discount->tax1 = $model->discount_tax;
            $discount->tax2 = $model->discount_amount;
            $discount->partno = 'discount';
            $discount->warehouse = '0000'; 
            $itemsList[]   = $discount->attributes;
            
        }
        Yii::app()->clientScript->registerScript('itemlist', "var invoiceLedgerList=" . json_encode($itemsList), CClientScript::POS_HEAD);
        $invoiceEmpList     = InvoiceEmp::model()->findAll('invoice=:invoice', array('invoice' => $model->invoice));
        $invoiceEmpArray    = array();
        foreach ($invoiceEmpList as $i => $item)
        {
            $invoiceEmpArray[] = $item->attributes;
            if ($item->employee != NULL)
            {
                $invoiceEmpArray[$i]['employeetext'] = $item->employee->firstname . ' ' . $item->employee->lastname;
            }
        }
        Yii::app()->clientScript->registerScript('empList', "var empList =" . json_encode($invoiceEmpArray), CClientScript::POS_HEAD);
 $transList = $model->getTransactionsList();
        $transData = array();
        foreach ($transList as $i=> $trans){
            $transData[$i]=array();
            $dateArray = explode('-',$trans['TxnDate']);

            $transData[$i]['date'] =$dateArray[1].'/'.intval($dateArray[2]).'/'.$dateArray[0];
            
            $transData[$i]['type'] =$trans['TxnType'];
            $transData[$i]['amount'] =$trans['Amount'];
            $transData[$i]['TxnID'] =$trans['TxnID'];
        }
        Yii::app()->clientScript->registerScript('transList', "var transList =" . json_encode($transData), CClientScript::POS_HEAD);
        $renderView = false;
        switch ($model->invoicetype)
        {
            case Invoice::TYPE_QUOTE:
                if ($model->getSalesOrders() != NULL)
                {
                    $renderView = true;
                }
                break;
            case Invoice::TYPE_SALES_ORDERS:
                if ($model->getInvoiceModel() != NULL)
                {
                    $renderView = true;
                }

                break;
            case Invoice::TYPE_INVOICE:
                if (($model->isEditable() == false)||$model->getPostedQuickBookText()=='Yes')
                {
                    $renderView = true;
                }
                break;
            case Invoice::TYPE_CREDIT_MEMO:
                if (($model->isEditable() == false)||$model->getPostedQuickBookText()=='Yes')
                {
                    $renderView = true;
                }
                break;
        }

        //post the tax to javascript
        $tax = $model->getTaxModel();
        if ($tax == NULL)
        {
            throw new CHttpException(500, 'Please update zipcode in '
                    . CHtml::link('Location', $this->createUrl('/locations/update', array('custno' => $model->custno, 'locno' => $model->locno))));
        }
        $tax = CJSON::encode($tax->attributes);
        $isNex = $model->checkNex()?'true':'false';
        Yii::app()->clientScript->registerScript('tax', "
                var TAX_EXEMPT_YES=" . Locations::TAX_EXEMPT_YES . ";
                var TAX_EXEMPT_NO=" . Locations::TAX_EXEMPT_NO . ";
                var tax=$tax;
                var isExempt={$model->location->isexempt};
                var useNexTax = $isNex;
                ", CClientScript::POS_HEAD);
		Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/restrictiveFileUpload.js', CClientScript::POS_BEGIN);
        //switch between view only and editable
        InvoiceUnlocker::increaseUnlockInvoiceViewCount($invoice);
        if (InvoiceUnlocker::isInvoiceUnlocked($invoice))
        {
            $renderView = false;
        }


        if ($renderView)
        {
            $this->render('view', array(
                'model' => $model,
                'type'  => $model->invoicetype,
                    )
            );
            return;
        }
        else
        {
            $this->render('update', array(
                'model' => $model,
                'type'  => $model->invoicetype,
                    )
            );
            return;
        }
    }

    public function actionCreate($custno, $locno, $type)
    {
        $model      = new Invoice;
        $location   = Locations::model()->find('custno =:custno AND locno=:locno', array(
            'custno'    => $custno,
            'locno'     => $locno
                ));
        if ($location == NULL)
        {
            throw new CHttpException(404, 'Invalid input data');
        }
        $customer = $location->customer;
        /* @var $location Locations */
        /* @var $customer Customers */
        if ($model->getInvoiceTypeValue($type) == NULL)
        {
            throw new CHttpException(404, 'Invalid input invoice type');
        }
        $model->invoicetype     = $type;
     
        $model->custno          = $custno;
        $model->locno           = $locno;
        $model->shipaddress1    = $location->add1;
        $model->shipaddress2    = $location->add2;
        $model->shipCSZ         = "$location->city $location->state $location->zip";
        $model->shipname        = $location->locname;      
        $model->taxcode         = $location->taxcode;
        $model->salesperson     = $customer->salesperson;
        $model->pricecode       = $customer->pricecode;
        $model->slterms         = $customer->terms;      
        $model->status          = 1;
        if($type == Invoice::TYPE_CREDIT_MEMO)
            $model->postedQuickBook = Invoice::QUICKBOOK_NO;
        if ($model->save())
        {
            //$this->sendInvoiceEmail($model->invoice);
            $this->redirect(array('invoices/update', 'invoice' => $model->invoice));
        }
    }

    public function actionCreateContractQuote($contractid)
    {
        $contract = Contracts::model()->findByPk($contractid);
        if ($contract == NULL)
        {
            throw new CHttpException(404, 'The contract does not exist.');
        }
        $prequoteList = ContractLedger::model()->findAll('contractid=:contractid', array(
            'contractid' => $contractid));
        if (count($prequoteList) == 0)
        {
            throw new CHttpException(500, 'You need to provide Pre-Quote to create Quote');
        }
        /* @var $contract Contracts */
        $location               = $contract->location;
        $model                  = new Invoice();
     
        $model->invoicetype     = Invoice::TYPE_QUOTE;
        $customer               = $location->customer;
        $model->jobnumber       = NULL;
        $model->custno          = $contract->custno;
        $model->locno           = $contract->locno;
        $model->shipaddress1    = $location->add1;
        $model->shipaddress2    = $location->add2;
   
        switch($contract->contractype){
			case 1 : 
					  $model->department      = '05';
					break;
			case 2 :
					 $model->department      = '07';
					break;
			case 3 :
					$model->department      = '08';
					break;
					    case 4:
                $model->department      = '10';
                break;
			}
        $model->shipCSZ         = "$location->city $location->state $location->zip";
        $model->purchasedby     = $contract->purchasedby;
        $model->shipname        = $location->locname;        
        $model->taxcode         = $location->taxcode;
        //$model->department=$job->department;
        //some default setting from parent company
        $customer               = $model->customer;
        $model->salesperson     = $customer->salesperson;
        $model->pricecode       = $customer->pricecode;
        $model->slterms         = $customer->terms;     
        $model->status          = 1;
        $model->agreementno     = $contractid;
        //$model->ponumber = $contract->customerpo;
   if($contract->discounted){
            $model->discounted = 1;
            $model->discount_percent = $contract->discount_percent;
            $model->discount_memo = $contract->discount_memo;	
            $model->discount_amount = $contract->discount_amount;
            $model->discount_total = $contract->discount_total;
            $model->discount_tax = $contract->discount_tax;
        }
        if ($model->save())
        {
            foreach ($prequoteList as $item)
            {
                /* @var $item ContractLedger */
                $newItem                = new InvoiceLedger;
                $newItem->attributes    = $item->attributes;
                $newItem->price         = $item->price;
                $newItem->taxed         = $item->taxed;
                $newItem->description   = $item->description;
                $newItem->qty           = $item->qty;
                $newItem->cost          = $item->cost;
                $newItem->noprint       = $item->noprint;
                $newItem->invoice       = $model->invoice;
                $newItem->id            = NULL;
                $newItem->setIsNewRecord(true);

				if($contract->contractype==4)
                $newItem->save(false);
                else $newItem->save();
            }
            $model  ->save();
            //$this   ->sendInvoiceEmail($model->invoice);
            $this   ->redirect(array('update', 'invoice' => $model->invoice));
        }
        else
        {
            //echo CJSON::encode($model->getErrors());
            throw new CHttpException(500, 'We get error while process your request. That is all we know');
        }
    }

    public function actionCreateQuote($jobnumber)
    {
        /*
          $location = Locations::model()->findByPk($locid);
          if($location==NULL){

          throw new CHttpException(404, 'The requested page does not exist.');
          }
         */

        $job = Jobs::model()->findByPk($jobnumber);
        if ($job == NULL)
        {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        

            $model = Invoice::model()->createQuoteByJob($jobnumber);


            if ($model != NULL)
            {
                //$this->sendInvoiceEmail($model->invoice);
                $this->redirect(array('update', 'invoice' => $model->invoice));
            }
            else
            {
                throw new CHttpException(500, 'We get error while process your request. That is all we know');
            }
       
    }

    public function actionCreateSalesOrders($quoteinvoice)
    {
        $quote = $this->loadModel($quoteinvoice);
        if ($quote->quotestatus != Invoice::STATUS_APPROVED)
        {
            throw new CHttpException('This quote is not approved');
        }
        $model = new Invoice();
        $model->attributes = $quote->attributes;
        $model->isNewRecord = true;
    
        $model->quoteorg = $quoteinvoice;
        $model->invoicetype = Invoice::TYPE_SALES_ORDERS;
        $model->salesorderstatus = Jobs::STATUS_OPEN;
        $model->clerk = null;
        if ($model->jobModel != NULL)
        {
            $model->jobModel->setJobAndBillStatus(Jobs::STATUS_OPEN);
            $model->jobModel->save();
        }
        //some default setting from parent company


        if ($model->save())
        {

            //delete all old sale orders
            Yii::app()->db->createCommand()->delete('tbl_invoice', 'quoteorg=:quote AND invoice!=:curInvoice', array(
                'quote' => $quoteinvoice,
                'curInvoice' => $model->invoice
            ));

            $model->copyInvoiceItemData($quoteinvoice);

            $model->save();
            //$this->sendInvoiceEmail($model->invoice);
            $this->redirect(array('update', 'invoice' => $model->invoice));
        }
        else
        {
            throw new CHttpException(500, 'We get error while process your request. That is all we know');
        }
    }
    public function actionCreateDispatchInvoice($dispatch){
        $dispatchModel = Dispatchdetails::model()->findByPk($dispatch);
        if($dispatchModel==null){
            throw new CHttpException('Can not find dispatch');
        }
        $location = $dispatchModel->location;
        $invoice = new Invoice();
        $invoice->custno = $dispatchModel->custno;
        $invoice->locno = $dispatchModel->locno;
        $invoice->dispatch = $dispatchModel->dispatch;
        $invoice->ponumber = $dispatchModel->ponumber;
        $invoice->department = '03';
        $invoice->shipaddress1 = $location->add1;
        $invoice->shipaddress2 = $location->add2;
        $invoice->shipCSZ = "$location->city $location->state $location->zip";
        $invoice->shipname = $location->locname;
        $invoice->period = DateUtil::getDefaultPeriod();
        $invoice->taxcode = $location->taxcode;
        $customer = $dispatchModel->customer;
        $invoice->salesperson = $customer->salesperson;
        $invoice->pricecode = $customer->pricecode;
        $invoice->slterms = $customer->terms;
        $invoice->invoicetype = 'Invoice';
        $invoice->invoicedate = DateUtil::getDefaultCurrentDateTime();
        $invoice->status = 1;
        $invoice->agreementno = NULL;

        if($invoice->save()){
            if($dispatchModel->wonumber !=null){
                $ledger = new InvoiceLedger();
                $ledger->partno = 'HIST';
                $ledger->description = 'W/O: '.$dispatchModel->wonumber;
                $ledger->invoice = $invoice->invoice;
                $ledger->save();                
            }
            $dispatchModel->invoice = $invoice->invoice;
            $dispatchModel->save();
            $this->redirect(array('update', 'invoice' => $invoice->invoice));    
        }else{
            var_dump($invoice->errors);
        }
        

        
    }
    public function actionCreateInvoice($saleinvoice)
    {
        $sale = $this->loadModel($saleinvoice);
        if ($sale->isInvoiceBelongToScheduleContract())
        {
            throw new CHttpException('This invoices have to be created under the payment schedule', 500);
        }
        if (JobsStatus::getText($sale->salesorderstatus) != 'Complete')
        {
            throw new CHttpException('Sales Order Status must be complete to continue', 500);
        }
        $model                  = new Invoice();
        $model->attributes      = $sale->attributes;
        $model->isNewRecord     = true;
      
        $model->salesordersorg  = $saleinvoice;
        $model->invoicetype     = Invoice::TYPE_INVOICE;
        $model->status          = 1;
        $model->clerk = null;

        //some default setting from parent company


        if ($model->save())
        { // create invoice
            $model->copyInvoiceItemData($saleinvoice);

            //update the inventoryact and inventory quanity
            //update all price again;
            $model->save();
          //  $this->sendInvoiceEmail($model->invoice);
            $this->redirect(array('update', 'invoice' => $model->invoice));
        }
        else
        {
            var_dump($model->getErrors());
        }
    }

    /*
     * Creat Credit Memo from a source Invoice
     */

    public function actionCreateCreditMemo($invoice)
    {
        $model = Invoice::model()->createCreditMemo($invoice);
        if ($model === NULL)
        {
            throw new CHttpException('Invoice can not be found');
        }
        else
        {
          //  $this->sendInvoiceEmail($model->invoice);
            $this->redirect(array('update', 'invoice' => $model->invoice));
        }
    }

    public function actionDelete($id)
    {

        $this->loadModel($id)->delete();
    }

    public function actionGetBillToData($id, $custno)
    {
        $data           = array();
        if ($id != 0)
            $model = Locations::model()->findByPk($id);
        else
        {
            $model = Customers::model()->findByPk($custno);
        };

        $data['add1']   = $model->add1;
        $data['add2']   = $model->add2;
        $data['csz']    = "$model->city $model->state $model->zip";
        echo json_encode($data);
    }

    /**
     * Returns the json endcoded item params(price, etc)
     * @param string item description
     */
    public function actionGetItemData($description)
    {

        //echo $description;

        $criteria       = new CDbCriteria;
        $criteria->compare('description', $description);
        $model          = Inventory::model()->find($criteria);


        $data           = array();
        $data['price']  = $model->baseprice;
        $data['partno'] = $model->partno;

        echo json_encode($data);
    }

    public function actionViewAll($type)
    {
        $this->render('viewall', array(
            'type' => $type
        ));
    }

    public function actionGetInvoiceLists($locno, $custno, $pk=NULL, $type=NULL, $page=1, $sort=NULL, $dir=NULL)
    {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;
        $crit = new CDbCriteria();
        $crit->compare('custno', $custno);
        $crit->compare('locno', $locno);
        if ($sort != NULL)
        {
            $order = CJSON::decode($sort);
            $crit->order = $order[0]['property'] . ' ' . $order[0]['direction'];
        }
        else
        {
            $crit->order = 'invoicetype, CAST( SUBSTR( invoice, LOCATE(  "-", invoice ) +1 ) AS SIGNED ) DESC';
        }
        $invoiceList = new CActiveDataProvider('Invoice', array(
                    'criteria'      => $crit,
                    'pagination'    => array(
                        'pageSize'      => 20,
                        'currentPage'   => $page,
                    ),
                ));

        $invoiceArr = array();
        if ($invoiceList->getTotalItemCount() > 0)
        {
            $invoiceArr['totalCount']   = $invoiceList->getTotalItemCount();
            $invoiceArr['type']         = 'Items';
            foreach ($invoiceList->getData() as $i => $item)
            {
                $invoiceArr['data'][]                   = $item->getAttributes();
                $invoiceArr['data'][$i]['amountdue']    = $item->getAmountOwned();

                //$invoiceArr['data'][$i]['total']=$item->getTotal();
            }
            echo json_encode($invoiceArr);
        }
        Yii::app()->end();
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Invoice::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function actionCheckQuoteApproved($quote)
    {
        $model = $this->loadModel($quote);
        if ($model->quotestatus == Invoice::STATUS_APPROVED)
        {
            echo 'true';
        }
        else
        {
            echo 'false';
        }
    }

    public function actionIsInvoiceCreatable($id)
    {
        //model is sales order
        $model = $this->loadModel($id);

        if ($model->isInvoiceBelongToScheduleContract())
        {
            echo 'This invoices have to be created under the payment schedule';
            Yii::app()->end();
        }
        if (JobsStatus::getText($model->salesorderstatus) != 'Complete')
        {

            echo 'In order to create Invoice, Sales Order status must be Complete';
        }
    }

    public function actionViewSalesOrder($invoice)
    {
        $model      = $this->loadModel($invoice);
        $salesOrder = $model->getSalesOrders();
        if ($model->invoicetype == Invoice::TYPE_QUOTE && $salesOrder != NULL)
        {
            $this->redirect(array('invoices/update', 'invoice' => $salesOrder->invoice));
        }
        else
        {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
    }

    public function actionViewInvoice($invoice)
    {
        $model          = $this->loadModel($invoice);
        $invoiceModel   = $model->getInvoiceModel();
        if ($model->invoicetype == Invoice::TYPE_SALES_ORDERS && $invoiceModel != NULL)
        {
            $this->redirect(array('invoices/update', 'invoice' => $invoiceModel->invoice));
        }
        else
        {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
    }

    public function actionSentBill($invoice, $soac=false)
    {
        $model = Invoice::model()->findByPk($invoice);
        if ($model->invoicetype == Invoice::TYPE_SALES_ORDERS)
        {
            if ($model->jobModel != NULL)
            {

                if ($soac == false)
                {
                    $model->jobModel->setJobAndBillStatus(NULL, Jobs::BILL_PENDING_SOACK);
                }
                else
                {
                    $model->jobModel->setJobAndBillStatus(Jobs::STATUS_PENDING_WANTDATE, Jobs::BILL_SOACK_50REQUESTED);
                }
                $model->jobModel->save();
            }
        }
    }

    public function sendInvoiceEmail($invoice)
    {
        $invoice = Invoice::model()->findByPk($invoice);
        $body = $this->renderPartial('invoiceEmail', array('invoice' => $invoice), true);           
        $subject = 'CC New ' . $invoice->invoicetype;
        return EmailUtil::sendEmail($subject,null,$body);
    }

    public function setOverEdit()
    {
        
    }

    public function actionUnlockInvoice($invoice)
    {
        if (InvoiceUnlocker::canRenderUnlockButton())
        {
            InvoiceUnlocker::unlockInvoice($invoice);
            $this->redirect(array('invoices/update', 'invoice' => $invoice));
        }
        else
        {
            throw new CHttpException('You can not unlock this invoice');
        }
    }

}

?>
